package com.weiaibenpao.demo.chislim.retrofit.rx;

import android.content.Context;
import android.support.annotation.NonNull;

import com.weiaibenpao.demo.chislim.utils.LoadingDialogUtils;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by wlx on 2017/12/5.
 * 被观察者
 */

public class LoadingTransformer<T> implements ObservableTransformer<T,T>{
    private final Context mContext;
    private final LoadingDialogUtils.Builder builder;


    public LoadingTransformer(@NonNull Context mContext) {
        this.mContext = mContext;
        builder = new LoadingDialogUtils.Builder(mContext).setTitle("正在加载...");
    }

    @Override
    public ObservableSource<T> apply(Observable<T> observable) {

        return observable.observeOn(AndroidSchedulers.mainThread()).
                doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        builder.show();
                    }
                }).doOnError(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                builder.dismiss();
            }
        }).doOnNext(new Consumer<T>() {
            @Override
            public void accept(T t) throws Exception {
                if (t==null){
                    builder.dismiss();
                }
                builder.dismiss();
            }
        });
    }
}
